package com.contextor.magiccards.game.auth.impl;

import com.contextor.magiccards.dao.utils.ShardHelper;
import com.contextor.magiccards.game.BaseGameManager;
import com.contextor.magiccards.game.auth.GameAuthenticationManager;
import com.contextor.magiccards.model.cards.MagicSchool;
import com.contextor.magiccards.model.character.Personage;
import com.contextor.magiccards.model.user.Account;
import com.contextor.magiccards.model.user.LoginItem;
import com.contextor.magiccards.model.user.User;
import com.contextor.magiccards.model.user.enums.UidType;
import org.springframework.stereotype.Service;

/**
 * User: sergey
 * Date: Mar 14, 2011 3:21:48 PM
 */
@Service
class GameAuthenticationManagerImpl extends BaseGameManager implements GameAuthenticationManager {

    public Boolean isUserRegistered(String uid) {
        logger.info("isUserRegistered; uid={}", uid);
        final User user = this.userService.findByUid(ShardHelper.getShard(uid), uid);
        return (user == null) ? Boolean.FALSE : Boolean.TRUE;
    }

    public User registerUser(String uid) {
        logger.info("registerUser; uid={}", uid);
        final int shard = ShardHelper.getShard(uid);
        final User user = new User();
        user.setId(uid);
        user.setUidType(UidType.VK);
        userService.save(shard, user);

        final Account account = new Account();
        account.setUser(user);
        accountService.save(shard, account);

        final Personage character = new Personage(user, user.getName(), MagicSchool.UNSELECTED);
        personageService.save(shard, character);
        return user;
    }

    public User authenticate(String uid) {
        logger.info("authenticate; uid={}", uid);
        final int shard = ShardHelper.getShard(uid);
        final User user = userService.findByUid(shard, uid);
        final LoginItem loginItem = new LoginItem(user, "localhost");
        historyService.save(shard, loginItem);
        return user;
    }
}
